<?php

namespace app\api\controller;

use support\Request;
use app\traits\CommonScript;
use app\api\model\PayHistory as PayHistoryDB;
use app\api\model\Wallets as Wallets;
use app\api\model\Yue as YueDB;
use Illuminate\Support\Carbon;

class PayGuideController
{
    public function index(Request $request)
    {
        return response(__CLASS__);
    }

    use CommonScript;

    public function pay(Request $request)
    {
        $req = [];
        $req['uid'] = $request->uid;
        $req['price'] = $request->post('price');
        $req['type'] = $request->post('type');
        $req['ip'] = $request->getRemoteIp();
        $res = $this->base_pay($req);
        $data = json_decode($res, true);
        if ($data['code'] == 200) {
            PayHistoryDB::insertGetId([
                "uid" => $req['uid'],
                "orderId" => $data['data']['orderId'],
                "orderNo" => $data['data']['orderNo'],
                "price" => $req['price'],
                "uip" => $req['ip'],
                "type" => $req['type'],
                'created_at' => Carbon::now()->toDateTimeString(),
            ]);
        }

        return $res;
    }

    public function query(Request $request)
    {
        $req['uid'] = $request->uid;
        $req['orderId'] = $request->post('orderId');
        $data = json_decode($this->pay_query($req), true);
        if($data['code']==200&&$data['data']['orderStatus']=='1'){
            $pay_type = PayHistoryDB::where('orderId',$req['orderId'])->value('status');
            if($pay_type!==1){
                PayHistoryDB::where('orderId',$req['orderId'])->update([
                    'status'=>1
                ]);
                $cash_db = Wallets::where('wallet_user_id', $req['uid'])->value('cash');
                Wallets::where('wallet_user_id', $req['uid'])->sharedLock()->update([
                    'cash' => $cash_db+$data['data']['amount'],
                ]);
                //添加余额记录
                YueDB::insertGetId([
                    'uid' => $req['uid'],
                    'count' =>$data['data']['amount'],
                    'type' => '在线充值',
                    'yu_e' =>$cash_db+$data['data']['amount'],
                    'created_at' => Carbon::now()->toDateTimeString()
                ]);
            }
        }

        $data = $this->pay_query($req);
        return $data;
    }


    public function query_balance(Request $request)
    {
        $res = $this->pay_query_balance();
        return $res;
    }


    public function payList(Request $request)
    {
        $uid = $request->uid;
        $res = PayHistoryDB::where('uid', 'like', '%' . $uid . '%')->orderBy('id', 'desc')
            ->paginate(10);
        return json([
            'code' => 2,
            'msg' => 'ok',
            'data' => $res,
        ]);
    }

    /**
     * 重置到账户
     * @param Request $request
     */
    public function payUser(Request $request)
    {

    }

}
